<template>
  <el-dialog v-model="visible" :title="`权限配置 - ${currentRole?.FName || ''}`" width="50%" destroy-on-close>
    <!-- 树的固定高度容器，内部滚动 -->
    <div class="tree-container">
      <el-tree
        ref="treeRef"
        :data="permissionTree"
        show-checkbox
        node-key="FId"
        :props="treeProps"
        :default-checked-keys="checkedKeys"
        :default-expanded-keys="expandedKeys"
        :highlight-current="false"
      />
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElTree } from "element-plus";
import { getRolePermissions, updateRolePermissions } from "@/api/modules/permission";

const visible = ref(false);
const treeRef = ref<InstanceType<typeof ElTree>>();
const currentRole = ref<any>(null);
const permissionTree = ref<any[]>([]);
const checkedKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]); // 存储要默认展开的节点keys

const treeProps = {
  label: "FName",
  children: "children"
};

// 打开弹窗
const open = async (role: any) => {
  currentRole.value = role;
  try {
    // 获取带 FHasPermission 的扁平数据
    const { data } = await getRolePermissions(role.FId);

    // 根据模块ID分类转树形结构
    permissionTree.value = transformToTreeByModule(data);
    // 提取选中 keys (只包含权限节点，不包含模块节点)
    checkedKeys.value = data.filter((p: any) => p.FHasPermission).map((p: any) => p.FId);
    // 设置默认展开所有模块节点
    expandedKeys.value = permissionTree.value.map(module => module.FId);

    visible.value = true;
  } catch (e) {
    console.error(e);
    ElMessage.error("获取权限数据失败");
  }
};

// 根据模块ID转为树形结构
const transformToTreeByModule = (list: any[]) => {
  // 先按模块分组
  const moduleMap = new Map<string, any>();

  list.forEach(item => {
    const moduleId = item.FModuleId;
    if (!moduleMap.has(moduleId)) {
      moduleMap.set(moduleId, {
        FId: `module_${moduleId}`, // 给模块节点添加前缀，避免与权限ID冲突
        FName: item.FModuleName,
        FModuleId: moduleId,
        children: []
      });
    }
    moduleMap.get(moduleId).children.push(item);
  });

  // 转换为数组并排序
  return Array.from(moduleMap.values()).sort((a, b) => a.FName.localeCompare(b.FName));
};

// 提交保存
const handleSubmit = async () => {
  try {
    const checked = (treeRef.value?.getCheckedKeys(false) as string[]) || [];
    const halfChecked = (treeRef.value?.getHalfCheckedKeys() as string[]) || [];

    // 过滤掉模块节点（以'module_'开头的ID）
    const allSelected = [...checked, ...halfChecked].filter(id => !id.toString().startsWith("module_"));

    await updateRolePermissions({
      FRoleId: currentRole.value.FId,
      FPermissionIds: allSelected
    });

    ElMessage.success("权限配置保存成功");
    visible.value = false;
  } catch (e) {
    console.error(e);
    ElMessage.error("保存失败");
  }
};

defineExpose({ open });
</script>

<style scoped>
.tree-container {
  max-height: 400px; /* 你可以调整高度 */
  padding-right: 8px; /* 防止滚动条遮挡内容 */
  overflow-y: auto;
}
</style>
